import json
import os
import datetime
import uuid
from typing import Dict, Any, List, Optional
from modules.ai_qa import DB  # 导入豆包模型接口


class ListManager:
    def __init__(self, output_dir="todo_lists"):
        self.project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.output_dir = os.path.join(self.project_root, output_dir)
        os.makedirs(self.output_dir, exist_ok=True)
        self.current_date = datetime.datetime.now().strftime("%Y-%m-%d")
        self.system_prompt = f"""
        今天的日期是 {self.current_date}。
        你是一个智能待办事项识别助手，请严格按照以下要求提取信息：
        - username: 用户名（默认为"未命名用户"，用户提及姓名时提取）
        - time: 事件时间（格式：YYYY-MM-DD HH:MM，未指定则默认今天 {self.current_date} 的当前时间）
        - event: 具体事项（需去除冗余信息，保留核心动作）

        输出要求：
        1. 仅返回标准JSON格式，不包含任何自然语言说明
        2. 时间字段必须包含日期和时分（如：{self.current_date} 14:30）
        示例输出：
        {{
            "username": "张三",
            "time": "{self.current_date} 15:30",
            "event": "去图书馆学习"
        }}
        """

    def parse_task(self, user_input: str) -> Dict[str, Any]:
        prompt = f"{self.system_prompt}\n用户输入：{user_input}"

        try:
            ai_response = DB(prompt, temperature=0.1)

            try:
                task_data = json.loads(ai_response.strip())
            except json.JSONDecodeError:
                print(f"JSON解析失败，使用默认任务: {ai_response[:50]}...")
                return self._get_default_task(user_input)

            task_data.setdefault("task_id", str(uuid.uuid4()))
            task_data.setdefault("username", "未命名用户")
            task_data.setdefault("time", datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
            task_data.setdefault("event", user_input.strip() or "无明确待办事项")

            return task_data

        except Exception as e:
            print(f"解析失败: {str(e)}")
            return self._get_default_task(user_input)

    def _get_default_task(self, user_input: str) -> Dict[str, Any]:
        return {
            "task_id": str(uuid.uuid4()),
            "username": "未命名用户",
            "time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
            "event": user_input.strip() or "无明确待办事项"
        }

    def save_task(self, task_data: Dict[str, Any]) -> str:
        timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        filename = f"task_{timestamp}.json"
        file_path = os.path.join(self.output_dir, filename)

        with open(file_path, "w", encoding="gbk", errors="replace") as f:
            json_str = json.dumps(task_data, ensure_ascii=False, indent=2)
            f.write(json_str)

        return file_path

    def process(self, user_input: str) -> str:
        task_data = self.parse_task(user_input)
        file_path = self.save_task(task_data)

        print("待办事项已生成：")
        print(json.dumps(task_data, ensure_ascii=False, indent=2))
        print(f"文件保存路径：{file_path}（GBK编码）")

        return file_path

    def delete_task(self, task_id: str) -> bool:
        for file in os.listdir(self.output_dir):
            file_path = os.path.join(self.output_dir, file)
            if os.path.isfile(file_path):
                try:
                    with open(file_path, "r", encoding="gbk") as f:
                        task_data = json.load(f)
                        if task_data.get("task_id") == task_id:
                            os.remove(file_path)
                            print(f"任务已删除：{task_id}")
                            return True
                except Exception as e:
                    print(f"删除任务时出错：{str(e)}")
        print(f"未找到任务ID：{task_id}")
        return False

    def list_tasks(self, sort_by_time: bool = False) -> List[Dict[str, Any]]:
        tasks = []
        for file in os.listdir(self.output_dir):
            file_path = os.path.join(self.output_dir, file)
            if os.path.isfile(file_path):
                try:
                    with open(file_path, "r", encoding="gbk") as f:
                        task_data = json.load(f)
                        if "task_id" not in task_data:
                            task_data["task_id"] = f"legacy_{uuid.uuid4()}"
                            print(f"检测到旧格式任务，已生成临时ID: {task_data['task_id']}")
                        tasks.append(task_data)
                except Exception as e:
                    print(f"跳过损坏文件: {file_path} ({str(e)})")

        if sort_by_time:
            tasks.sort(key=lambda x: x.get("time", ""), reverse=True)

        return tasks

    def search_tasks(self, keyword: str) -> List[Dict[str, Any]]:
        return [task for task in self.list_tasks()
                if keyword.lower() in str(task.get("event", "")).lower()
                or keyword.lower() in str(task.get("username", "")).lower()]

    def update_task(self, task_id: str, updates: Dict[str, Any]) -> bool:
        for file in os.listdir(self.output_dir):
            file_path = os.path.join(self.output_dir, file)
            if os.path.isfile(file_path):
                try:
                    with open(file_path, "r", encoding="gbk") as f:
                        task_data = json.load(f)
                    if task_data.get("task_id") == task_id:
                        for field in ["username", "time", "event"]:
                            if field in updates:
                                task_data[field] = updates[field]
                        with open(file_path, "w", encoding="gbk", errors="replace") as f:
                            json.dump(task_data, f, ensure_ascii=False, indent=2)
                        print(f"任务已更新：{task_id}")
                        return True
                except Exception as e:
                    print(f"更新任务时出错：{str(e)}")
        print(f"未找到任务ID：{task_id}")
        return False


# ======================
# 示例用法（纯文本输出）
# ======================
if __name__ == "__main__":
    manager = ListManager()

    # 创建任务
    task1 = manager.process("明天上午9点陈小雨去公园跑步")
    task2 = manager.process("后天下午3点李华参加会议")

    # 列出所有任务
    print("\n当前任务列表：")
    for task in manager.list_tasks(sort_by_time=True):
        print(f"- ID: {task['task_id'][:8]}... | {task['time']} | {task['username']} | {task['event']}")

    # 搜索任务
    print("\n搜索包含'会议'的任务：")
    for task in manager.search_tasks("会议"):
        print(f"- {task['event']}")

    # 更新任务
    if manager.list_tasks():
        task_id = manager.list_tasks()[0]["task_id"]
        manager.update_task(task_id, {"event": "明天上午9点陈小雨去公园晨跑"})

    # 删除任务
    if manager.list_tasks():
        task_id = manager.list_tasks()[0]["task_id"]
        manager.delete_task(task_id)
        print("\n删除后的任务列表：")
        for task in manager.list_tasks():
            print(f"- {task['event']}")